編譯ffmpeg 硬體加速的坑

前言

最近的案子..要幫同仁搞ffmpeg的機器,如果沒有使用顯卡加速是個很愉快的事情
但扯到顯卡就滿滿的坑了。

正文

環境:GKE,開啟GPU節點,詳細的使用方法可參考之前寫過的 GKE使用GPU
環境設定那部分,有開工單去問google,他們有說要改文件。

1.編譯時找不到 libnpp
ERROR: libnpp not found

安裝 CUDA Toolkit
ref.
How to install CUDA 9.2 on Ubuntu 18.04
CUDA Toolkit 11.2 Downloads

wget https://developer.download.nvidia.com/compute/cuda/11.2.0/local_installers/cuda_11.2.0_460.27.04_linux.run
sudo sh cuda_11.2.0_460.27.04_linux.run

安裝時,不要另外裝驅動,只裝cuda

  1. 參數設定編碼允許png,出現錯誤
    --enable-decoder=png --enable-encoder=png

Disabled png_decoder because not all dependencies are satisfied: zlib

需要先安裝 zlib

ref. ffmpeg & png watermark issue

apt-get install zlib1g-dev
  1. 編譯完成後,執行發生錯誤,找不到libnpp
    ffmpeg: error while loading shared libraries: libnppig.so.11: cannot open shared object file: No such file or directory

ref. libnppig.so.8.0 Missing FFmpeg
設定參數
export LD_LIBRARY_PATH=/usr/local/cuda-11.2/targets/x86_64-linux/lib

  1. 驅動不支援
    Driver does not support the required nvenc API version. Required: 11.0 Found: 9.0

The minimum required Nvidia driver for nvenc is 455.28 or newer
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

切到 nv-codec-headers 的資料夾底下,切換分支
git checkout sdk/9.0

ref. [記錄一個bug]關於運行ffmpeg with cuda出錯問題:Driver does not support the required nvenc API version..... [已解決|記錄一個bug]關於運行ffmpeg with cuda出錯問題:Driver does not support the required nvenc API version..... [已解決]

  1. 使用浮水印轉檔出現錯誤
    Impossible to convert between the formats supported by the filter 'graph 0 input from stream 0:0' and the filter 'auto_scaler_0'
    Error reinitializing filters!
    Failed to inject frame into filter network: Function not implemented

之前寫的

ffmpeg -hwaccel cuvid -y -i 49805.mp4 -i logo.png \
-filter_complex "[0]scale='min(1280,iw)':-1[bg];[1][bg]scale2ref=w='iw*15/100':h='iw*15/100*166/446'[wm][vid];[vid][wm]overlay=10:10" \
-c:v h264_nvenc ezio.mp4

會發生上面的錯誤(auto_scaler_0),但只要將 cuvid改成 nvdec 就正常了。

ffmpeg -hwaccel nvdec -y -i 49805.mp4 -i logo.png \
-filter_complex "[0]scale='min(1280,iw)':-1[bg];[1][bg]scale2ref=w='iw*15/100':h='iw*15/100*166/446'[wm][vid];[vid][wm]overlay=10:10" \
-c:v h264_nvenc ezio.mp4

ref. Filter complex through CUDA hevc_cuvid with FFMPEG input 4k hevc, help needed

  1. 轉碼時查詢 詳細的log記錄
    在ffmpeg的後面加上 -loglevel debug
    ref. FFMPEG的默認像素格式將圖像堆棧編碼為電影

  2. ffmpeg 常用指令

ffmpeg -hwaccels 查詢能用的硬體加速
ffmpeg -codecs | grep cuvid 查看ffmpeg支持的cuvid的編碼格式

ref. Ubuntu 16.04下編譯ffmpeg支持CUDA下的cuvid vnenc和NPP
使用GPU硬件加速FFmpeg視頻轉碼及排坑

其他參考項目
ref. Matching CUDA arch and CUDA gencode for various NVIDIA architectures
FFmpeg再學習 -- Linux 安裝說明(參數說明)
在k8s中調用NVIDIA-GPU
在k8s中調用NVIDIA-GPU(Dockerfile)